package com.ruoyi.framework.web.service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.SsoConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.mdm.utils.NoHttpsClientUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * SSO业务层
 *
 * @author
 */
@Service
public class SsoLoginService {
    private static final Logger log = LoggerFactory.getLogger(SsoLoginService.class);
    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    public String login(String code) {
        LoginUser loginUser = new LoginUser();
        String accessToken = "";
        try {
            //获取token
            accessToken = getToken(code);
            //获取用户信息
            loginUser = getSsoUser(accessToken);
        } catch (Exception e) {
            throw new GlobalException(e.getMessage());
        }
        return tokenService.createToken(loginUser);
    }

    private LoginUser getSsoUser(String accessToken) throws Exception {
        LoginUser loginUser = new LoginUser();
        RestTemplate restTemplate = NoHttpsClientUtils.getRestTemplate();
        String userInfoRequestUrl = SsoConfig.getUserInfoRequestUrl();
        HttpHeaders userInfoHeaders = new HttpHeaders();
        userInfoHeaders.add("Accept", "*/*");
        userInfoHeaders.add("Authorization", accessToken);
        HttpEntity<Object> reqEntity = new HttpEntity<>(userInfoHeaders);
        ResponseEntity<String> userInfoEntity = restTemplate.exchange(userInfoRequestUrl, HttpMethod.GET, reqEntity, String.class);
        String body = userInfoEntity.getBody();
        log.info("=============SSO用户信息==============:" + body);

        if (StringUtils.isNotEmpty(body)) {
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (!ObjectUtils.isEmpty(jsonObject)) {
                Object userPrincipalName = jsonObject.get("userPrincipalName");
                SysUser sysUser = userMapper.selectUserByUserName(userPrincipalName.toString());
                if (StringUtils.isNull(sysUser)) {
                    log.info("登录用户：{} 不存在.", userPrincipalName);
                    throw new GlobalException("user.not.exists");
                }
                loginUser = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
                recordLoginInfo(loginUser.getUserId());
            }
        }
        log.info("=============loginUser信息：==============" + loginUser);
        log.info("=============END==============");
        return loginUser;
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());

        SysUser localUser = userService.selectUserById(userId);
        sysUser.setSystemCodeStr(localUser.getSystemCodeStr());


        iSysUserService.updateUserProfile(sysUser);
    }

    private String getToken(String code) throws Exception {
        String token = "";
        RestTemplate restTemplate = NoHttpsClientUtils.getRestTemplate();
        String tokenRequestUrl = SsoConfig.getTokenRequestUrl();
        tokenRequestUrl = String.format(tokenRequestUrl, SsoConfig.getTenantId());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "*/*");
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 设置urlencoded数据
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("client_id", SsoConfig.getClientId());
        map.add("client_secret", SsoConfig.getClientSecret());
        map.add("grant_type", SsoConfig.getGrantType());
        map.add("code", code);
        map.add("redirect_uri", SsoConfig.getRedirectUri());
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<String> postForEntity = restTemplate.postForEntity(tokenRequestUrl, httpEntity, String.class);
        String body = postForEntity.getBody();
        log.info("=============获取token接口返回数据============：" + body);
        if (StringUtils.isNotEmpty(body)) {
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (!ObjectUtils.isEmpty(jsonObject)) {
                Object accessToken = jsonObject.get("access_token");
                if (!ObjectUtils.isEmpty(accessToken)) {
                    token = String.valueOf(accessToken);
                    log.info("=============token值============：" + token);
                }
                Object expiresIn = jsonObject.get("expires_in");
            }
        }
        log.info("=============End============");
        return token;
    }

    public Map<String, String> checkToken(String state, String token) {
        HashMap<String, String> result = new HashMap<>();
        try {
            checkPermission(token, state, result);
        } catch (Exception e) {
            throw new GlobalException(e.getMessage());
        }
        return result;
    }

    private void checkPermission(String accessToken, String state, HashMap<String, String> result) throws Exception {
        result.put("token", accessToken);
        RestTemplate restTemplate = NoHttpsClientUtils.getRestTemplate();
        String userInfoRequestUrl = SsoConfig.getUserInfoRequestUrl();
        HttpHeaders userInfoHeaders = new HttpHeaders();
        userInfoHeaders.add("Accept", "*/*");
        userInfoHeaders.add("Authorization", accessToken);
        HttpEntity<Object> reqEntity = new HttpEntity<>(userInfoHeaders);
        ResponseEntity<String> userInfoEntity = null;
        try {
            userInfoEntity = restTemplate.exchange(userInfoRequestUrl, HttpMethod.GET, reqEntity, String.class);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("token", "");
            return;
        }
        String body = null;
        if (ObjectUtils.isNotEmpty(userInfoEntity)) {
            body = userInfoEntity.getBody();
        }
        log.info("=============SSO用户信息==============:" + body);
        String decode = URLDecoder.decode(state, "UTF-8");
        JSONObject stateObj = JSONObject.parseObject(decode);
        String approvalFormCode = stateObj.getString("approvalFormCode");
        String isAgree = stateObj.getString("isAgree");
        result.put("approvalFormCode", approvalFormCode);
        result.put("isAgree", isAgree);

        String approverEmailAddress = stateObj.getString("emailAddress");
        if (StringUtils.isNotEmpty(body)) {
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (!ObjectUtils.isEmpty(jsonObject)) {
                String userPrincipalName = jsonObject.getString("userPrincipalName");
                String mail = jsonObject.getString("mail");
                if (!approverEmailAddress.equals(mail)) {
                    throw new GlobalException("登录用户：" + userPrincipalName + "，邮箱：" + mail + "与当前邮件审批人不一致！");
                }
//                //根据审批单code查询审批单，获取一级审批人和审批单状态
//                ApprovalForm approvalForm = approvalFormMapper.selectApprovalFormByApprovalFormCode(approvalFormCode);
//                if (ObjectUtils.isEmpty(approvalForm)) {
//                    throw new GlobalException("审批单：" + approvalFormCode + "不存在！");
//                }
//                String brandManagerEmail = approvalForm.getBrandManagerEmail();
//                String status = approvalForm.getStatus();
//                result.put("status", status);
//                //查询审批配置人的二级和三级审批人
//                List<ApproverConfig> approverConfigList = approverConfigMapper.selectApproverConfigList(new ApproverConfig());
//                if (CollectionUtils.isEmpty(approverConfigList)) {
//                    throw new GlobalException("审批的二三级审批人不存在！");
//                }
//                ApproverConfig approverConfig = approverConfigList.get(0);
//                String secondApproverEmail = approverConfig.getSecondApproverEmail();
//                String threeApproverEmail = approverConfig.getThreeApproverEmail();
//                if (mail.equals(secondApproverEmail)) {
//                    result.put("level", "1");
//                } else if (mail.equals(brandManagerEmail)) {
//                    result.put("level", "2");
//                } else if (mail.equals(threeApproverEmail)) {
//                    result.put("level", "3");
//                } else {
//                    throw new GlobalException("登录用户：" + userPrincipalName + "不是该审批单的一级/二级/三级审批人！");
//                }
                result.put("level", "1");
            }
        }
        log.info("=============END==============");
    }


}
